package com.lv.common.utils

import android.graphics.Color
import android.os.Handler
import android.widget.TextView
import com.lv.common.R

/**
 * 作者： ygx
 * 创建日期：2023/3/2 4:56 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：isBg 是否起用背景
 */
class TimerUnit(private val textView: TextView, private val isBg: Boolean = true,) : Handler() {
    private var defaultTime = 60
    private var time = defaultTime
    private var isShowEndText = true

    private var timeEndListener: OnTimeEndListener? = null

    private var runnable: Runnable = object : Runnable {
        override fun run() {
            time--
            if (time == 0) {
                endtTime()
                return
            }
            textView.text = String.format("%dS", time)
            postDelayed(this, 1000)
        }
    }

    fun setTimeEndListener(timeEndListener: OnTimeEndListener) {
        this.timeEndListener = timeEndListener
    }

    fun setShowEndText(showEndText: Boolean) {
        isShowEndText = showEndText
    }


    fun setTime(time: Int) {
        this.defaultTime = time
        this.time = defaultTime
    }

    fun startTime() {
        post(runnable)
        if (isBg) {
            textView.setBackgroundResource(R.drawable.bg_e1_line_14)
            textView.setTextColor(Color.parseColor("#999999"))
        }
        textView.isEnabled = false
    }


    fun pauseTime() {
        removeCallbacks(runnable)
        time = defaultTime
    }

    fun endtTime() {
        if (isShowEndText) {
            textView.text = "获取验证码"
            if (isBg) {
                textView.setTextColor(Color.parseColor("#ffffff"))
            }
        }
        if (isBg) {
            textView.setBackgroundResource(R.drawable.bg_color_theme_buttom_14)
        }
        textView.isEnabled = true
        removeCallbacks(runnable)
        time = defaultTime
        if (timeEndListener != null) {
            timeEndListener!!.timeEnd()
        }
    }

    interface OnTimeEndListener {
        fun timeEnd()
    }

}